package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.sys.modular.system.service.ZxTzqkService;
import cn.stylefeng.guns.sys.modular.system.service.ZxYusuanService;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;

@Service
public class TransService {

    @Resource
    private ZxYusuanService zxyusuanService;
    @Resource
    private ZxTzqkService zxTzqkService;


    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public ResponseData handFile(File f) throws Exception {
        String fname = f.getName();
        FileInputStream fis = new FileInputStream(f);
//            Workbook workBook = getWorkBook(fis);
        Workbook workBook = WorkbookFactory.create(f);
        Sheet firstsheet = workBook.getSheetAt(0);
        Sheet yusuansheet = workBook.getSheetAt(1);

        //处理sheet1 投资情况
        ResponseData rs1 = zxTzqkService.mdtzqkHander(firstsheet);
        if(rs1.getCode()!=ResponseData.DEFAULT_SUCCESS_CODE){
            return rs1;
        }
        Object data = rs1.getData();
        if(ToolUtil.isNotEmpty(data)){
            Long mdid=Long.valueOf(data.toString());// 第2个sheet门店名不做判断， 以第一个sheet的门店为准
            //处理sheet2 预算数据
            ResponseData rs2 = zxyusuanService.yusuanSheet(yusuansheet,mdid);
            if(rs2.getCode()!=ResponseData.DEFAULT_SUCCESS_CODE){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return rs2;
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ErrorResponseData("导入错误");
        }
    }
}
